package edu.ucsb.android.APMap;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.LinkedList;
import java.util.List;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import edu.ucsb.APMap.util.APInfo;

public class UdpReceiver implements Runnable{
	Handler apInfoHandler;
	private static final int CLIENTPORT = 4234;
	private static String CLIENTADDR = "169.254.87.205";
	
	public UdpReceiver(Handler handler){
		apInfoHandler = handler;
	}

	@Override
	public void run() {
		InetAddress addr;
		try {
			addr = InetAddress.getByName(CLIENTADDR);
			DatagramSocket socket = new DatagramSocket(CLIENTPORT, addr);
	        byte[] receiveData = new byte[1024];
	        while(true)
	           {
				  Log.d("###########", "android is listening on port 1234");
	        	  DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
				  socket.receive(receivePacket);
				  byte[] content = receivePacket.getData();
				  String wifiString;
				  if(content[0] == 'a'){
					  List<APInfo> info = new LinkedList<APInfo>();
					  wifiString = new String(content, 2, content.length-2);
					  String[] aps = wifiString.split(";");
					  for(String ap: aps){
						  Log.d("ap info", "###### " + ap);
						  String[] items = ap.split(",");
						//public APInfo(String bSSID, String sSID, String capabilities, double frequency, double longtitude, double latitude)
						  //apInfos += bssid + ", " + ssid + ", " + capabilities + ", " + frequency + ", " + longtitude + ", " + latitude + ";";
						  APInfo oneAp = new APInfo(items[0], items[1], items[2], Double.parseDouble(items[3]), Double.parseDouble(items[4]) , Double.parseDouble(items[5]));
						  info.add(oneAp);
					  }
					  Message msg = new Message();
					  msg.obj = info;
					  apInfoHandler.sendMessage(msg);
				  }
	           }
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}

	
	
}
